# -*- codeing = utf-8 -*-
# import io
# import sys
# from bs4 import BeautifulSoup # 网页解析，获取数据
# import re #睁着表达式进行文字匹配
# import urllib.request,urllib.error #定制url获取网页数据
# import xlwt #进行excel操作
# import sqlite3
import urllib.request
import urllib.parse
import urllib.error
from bs4 import BeautifulSoup
import re


def main():
    print('main part')
    baseurl = "https://movie.douban.com/top250?start=0"
    # 1.爬取网页
    # datalist = getData(baseurl)
    getData(baseurl)
    # 3.保存数据
    # savepath = '.\\豆瓣电影Top250.xls'
    # saveData(datalist, savepath)


findLink = re.compile(r'<a href="(.*?)">', re.S)  # 创建正则表达式对象，表示规则（字符串的模式）
findImgSrc = re.compile(r'src="(.*?)"', re.S)  # re.S让换行符包含在字符中
# findNames = re.compile(r'<span class="title">(.*?)</span>', re.S)
# findOtherNames = re.compile(r'other">(.*?)</span>', re.S)
# 标题
findTitle = re.compile(r'<span class="title">(.*?)</span>')
# 评分
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*?)</span>')
# 评论人数
findJudge = re.compile(r'<span>(\d*)人评论</span>')
# 概况
findInq = re.compile(r'<span class="inq">(.*?)</span>')
# 相关内容
findbd = re.compile(r'<p class="">(.*?)</p>', re.S)


# 爬取网页
def getData(baseurl):
    # result = askURL(baseurl)
    # print(result)
    data = []
    for i in range(0, 1):
        url = baseurl + str(i * 25)
        result = askURL(url)
        bs = BeautifulSoup(result, 'html.parser')
        # bs.find_all('href')
        # resultlist = bs.find_all('li')
        resultlist = bs.find_all('div', class_='item')
        # resultlist = bs.find_all(class_= True)
        # resultlist = bs.select(class_= 'bd')
        # resultlist = bs.find_all(class_='item')
        # resultlist = bs.select("div[class='item']")
        # resultlist = bs.find_all(re.compile('a'))
        # print('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
        # print(resultlist)
        part = []
        for item in resultlist:
            item = str(item)
            link = re.findall(findLink, item)[0]
            imgsrc = re.findall(findImgSrc, item)[0]
            title = re.findall(findTitle, item)
            ratenum = re.findall(findRating, item)[0]
            judgenum = re.findall(findJudge, item)
            # 概论
            inq = re.findall(findInq, item)[0]  
            if len(inq) > 0:
                inq = inq.replace('。', '')
            else:
                inq = ' '
            bd = re.findall(findbd, item)[0]
            bd = re.sub('<br(\s+)?/>(\s+)?', "", bd)  #去掉</br>
            bd = re.sub('/', " ", bd)
            part.append(title[0])
            if (len(title) == 2):
                foreignname = title[1].replace("/", "")
                part.append(foreignname)
            else:
                part.append(' ')
            part.append(link)
            part.append(imgsrc)
            part.append(ratenum + '人评价')
            part.append('综合评分' + str(judgenum))
            part.append('概况' + inq)
            part.append('相关' + bd)
            data.append(part)
            print(part)
            # print(names)
            # chineseName = names[0]
            # subName = names[1]
            
            # othernames = re.findall(findOtherNames, item)[0]
            # print(chineseName + subName + othernames)
    
    # print(data)


def saveData(data, path):
    print('save...')


def askURL(url):
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:78.0) Gecko/20100101 Firefox/78.0'}
    request = urllib.request.Request(url, headers=headers)
    html = ''
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode('utf-8')
        # print(html)
    except urllib.error.URLError as e:
        if hasattr(e, 'code'):
            print('errorcode' + e.code)
        elif hasattr(e, 'reaseon'):
            print('erroreason' + e.reason)
    return html


main()



# # post请求数据拉取
# data = bytes(urllib.parse.urlencode({'hello': 'world'}), encoding='utf-8')
# try:
#     response = urllib.request.urlopen('http://httpbin.org/post', data=data,timeout=1)
#     print(response.read().decode('utf-8'))
# except urllib.error.URLError as e:
#     print(e.reason)
#     print('time out')

